<template>
  <div class="p-15 p-t-0">
    <div class="table-padding orderDialog ">
      <el-form :model="modelForm" ref="modelForm" >
        <div class="text-left">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item prop="name" :rules="[]" >
                <el-input placeholder="商品名称" v-model="dishes.name" :disabled="noEdit" size="medium">
                  <template slot="prepend">
                    <el-tooltip placement="top" content="商品名称">
                      <el-button>商品名称</el-button>
                    </el-tooltip>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="warehouses" :rules="[]">
                <div class="el-input  el-input-group el-input-group--prepend el-input--medium">
                  <div class="el-input-group__prepend">
                    <el-button>出库仓库</el-button>
                  </div>
                  <el-select v-model="modelForm.warehouseId" placeholder="请选择" class="w-100p" :disabled="isEdit">
                    <el-option
                      v-for="item in warehouses"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--rules.numPot-->
              <el-form-item prop="processQty" :rules="[]">
                <el-input placeholder="加工份数" v-model.number="modelForm.processQty" size="medium" @focus="printNum" :disabled="isEdit">
                  <template slot="prepend">
                    <el-tooltip placement="top" content="加工份数">
                      <el-button>加工份数</el-button>
                    </el-tooltip>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item prop="materialCost" :rules="[]">
                <el-input placeholder="原料成本" v-model.number="modelForm.materialCost" @input="getSumCost(modelForm)" :disabled="noEdit" size="medium">
                  <template slot="prepend">
                    <el-tooltip placement="top" content="原料成本">
                      <el-button>原料成本</el-button>
                    </el-tooltip>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!--rules.numPot2-->
              <el-form-item prop="otherCost" :rules="[rules.numPot2]">
                <el-input placeholder="其他成本" size="medium" :disabled="isEdit" v-model.number="modelForm.otherCost" @focus="printNum"  @blur="getSumCost(modelForm),priceValidate(modelForm,'otherCost')">
                  <template slot="prepend">
                    <el-tooltip placement="top" content="其他成本">
                      <el-button>其他成本</el-button>
                    </el-tooltip>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="cost" :rules="[]">
                <el-input placeholder="合计成本"  size="medium" v-model.number="modelForm.cost" @blur="priceValidate(modelForm,'cost')"  :disabled="noEdit">
                  <template slot="prepend">
                    <el-tooltip placement="top" content="合计成本">
                      <el-button>合计成本</el-button>
                    </el-tooltip>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item prop="no" :rules="[]">
            <el-input type="text" v-model="modelForm.remark" auto-complete="off" placeholder="请输入备注信息" :disabled="isEdit" size="medium">
              <template slot="prepend">
                <el-button>备注</el-button>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <div class="materialCostTable">
          <el-form-item class="text-left">
            <el-button type="primary" @click="submitForm('modelForm')" size="medium"><i class="icon icon-baocun"></i> 保存</el-button>
            <el-button type="danger" @click="goBack()" size="medium"><i class="icon icon-fanhui1"></i> 取消</el-button>
          </el-form-item>

          <div class="center-center">
            <el-table
              :data="tableData"
              border
              show-summary
              :summary-method="getSummaries" style="position: relative">
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column
                width="80">
                <template scope="scope">
                  <span class="el-icon-plus" style="cursor: pointer;font-size: 10px;padding-right: 5px" @click="addColumn(scope.$index)"></span>
                  <span class="el-icon-minus" style="cursor: pointer;font-size: 10px;padding-left: 5px" @click="minusColumn(scope.$index)"></span>
                </template>
              </el-table-column>
              <el-table-column
                prop="code"
                label="物料编号"
                width="150">
                <template  slot-scope="scope">
                  <div style="position: relative">
                    <el-select v-model="scope.row.code" :disabled="isEdit" remote @change="codeChange(scope.$index)"   :remote-method="remoteMethod"
                               filterable="" allow-create placeholder="请输入原料编号">
                      <el-option v-for="(item,index) in material" :disabled="(item.state && item.state!='NORMAL')" :key="index"
                                 :label="item.code" :value="item.no">
                        <div style="width:100px;border-bottom:1px solid #c0c0c0;padding:5px 0px">
                          {{item.no}}
                        </div>
                      </el-option>
                    </el-select>
                    <span class="el-icon-more" @click="handleIconClick(scope.$index)"
                          style="cursor: pointer;font-size: 10px;padding-right: 5px; position: absolute;right: 10px;top: 40%"></span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="原料名称"
                width="150" >
              </el-table-column>
              <el-table-column
                prop="spec"
                label="规格型号"
                width="150" >
              </el-table-column>
              <el-table-column
                prop="unit"
                label="库存单位">
              </el-table-column>
              <el-table-column
                prop="consumeUnit"
                label="消耗单位">
              </el-table-column>
              <el-table-column
                prop="count"
                label="消耗数量">
                <template scope="scope">
                  <el-input v-model="scope.row.count" :disabled="isEdit" @focus="printNum()"  @blur="getPrice(scope.row),priceValidate(scope.row,'count')"  placeholder="0.00"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="orderPriceBom"
                label="原料单价"
              >
                <template scope="scope">
                  <span>{{scope.row.orderPriceBom | money }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="price"
                label="理论金额">
                <template scope="scope">
                  <span v-if="scope.row.consumeRates>0">{{scope.row.orderPriceBom*scope.row.count/scope.row.consumeRates | moneyFor(4) }}</span>
                  <span v-if="scope.row.consumeRates==0">{{scope.row.orderPriceBom*scope.row.count | moneyFor(4) }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="isMain"
                label="是否主料">
                <template scope="scope"><el-checkbox v-model="scope.row.isMain" style="line-height: normal !important;"></el-checkbox></template>
              </el-table-column>
              <el-table-column
                prop="memo"
                label="备注">
                <template scope="scope"><el-input v-model="scope.row.memo" :disabled="isEdit"  placeholder=""></el-input></template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form>
    </div>
    <materialsCostSelect :isShow="dialogTableVisible"  v-on:pushData="getData" v-on:closeDialog="dialogTableVisible=false"></materialsCostSelect>
  </div>
</template>
<script>
  import materialsCostSelect from "@/components/materialsCostSelect.vue"
  //注意路径
  export default{
    data(){
      return {
        dialogTableVisible:false,
        noEdit:true,
        material:[],
        pageSizeSet:window.pageSizes,
        pageSize:window.pageSize,
        inputText:"",
        content:"",
        tableData: [{
          id:"",
          code: '',
          name: '',
          purchaseSpec: '',
          consumeUnit:'',
          unit:'',
          unitId:'',
          count:'0',
          newPrice:"",
          orderPriceBom:'0.00',
          price:'0.00',
          memo:'',
          isMain:false,
          consumeRates:"0.00"

        }],
        isEdit:false,
        modelForm: {},
        warehouses:[],
        dishes:{},
        restaurants: [],
        timeout:  null,
        selectRow:[],
        gridData: [],
        itemActive:0,
        data: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      };
    },
    components: {
      materialsCostSelect
    },
    created(){
      window.this = this;
      console.log(this.$route.query.type!=undefined);
      if(this.$route.query.type){
        this.isEdit=true;
        console.log("3333333")
      }else{
        this.isEdit=false;
        console.log("44444")
      }
      console.log(this.isEdit)
      this.initData();

    },

    methods: {
      printNum(){
        event.currentTarget.select();
      },
      //页面第一次进来获取表单需要的数据
      initData(){
        var id=this.$route.query.id;
        var dishesId=this.$route.query.dishesId;
        var storeId=this.$route.query.storeId;
        var query="";
        if(id!=null && id!=""){   //规格id
          query="?id="+dishesId+"&specId="+id+"&storeId="+storeId;
//                    this.modelForm.id=id;
        }

        this.$axios.get("branchstores/materialCosts/create"+query).then(data=>{
          if(data.status==200){
            var dataValue=data.content;
            this.modelForm=dataValue.materialCost;
            this.modelForm.dishesId=dishesId;
            this.modelForm.specId=id;
            this.modelForm.storeId=storeId;
            this.warehouses=dataValue.warehouseList;
            this.dishes=dataValue.dishes;
            for(var i=0;i<dataValue.materialCostDetail.length;i++){
              dataValue.materialCostDetail[i].spec=dataValue.materialCostDetail[i].goodsSpec;
            }
            this.material=dataValue.materialCostDetail;
            this.tableData=dataValue.materialCostDetail;
          }else{
            this.$message.error(data.message);
          }
        })

      },
      getSumCost(item){
        if(this.modelForm.materialCost && this.modelForm.otherCost){
          this.modelForm.cost=(this.modelForm.materialCost*1+this.modelForm.otherCost*1).toFixed(4);
        }else{
          this.modelForm.cost=0.0
        }
      },
      getPrice(item){
        if(item.consumeRates>0 && item.count>0){
          if(item.orderPriceBom>0){
            item.price=((item.orderPriceBom*item.count)/item.consumeRates*1).toFixed(2);
          }
          if(item.purchaseNewPrice>0){
            item.newPrice=((item.purchaseNewPrice*item.count)/item.consumeRates*1).toFixed(2);
          }
        }else{
          item.price="0.00";
          item.newPrice="0.00";
        }

        // item.newPrice=item.count*item.purchaseNewPrice;//最新价格=数量*最新采购单价
        // item.cost=item.materialCost+item.otherCost;
      },
      inputClick(){
        this.selectGood("");
      },
      newLabel(newList){
        if(newList){
          for(var i=0;i<newList.length;i++){
            newList[i].label=newList[i].name;
            if(newList[i].children){
              this.newLabel(newList[i].children)
            }
          }
        }
      },
      priceValidate(item,key) {
        var isNum = /^0$|^[1-9]\d{0,15}$|^[1-9]\d{0,15}\.{1}\d{1,4}$|^0\.{1}\d{1,4}$/g;
        if (!isNum.test(item[key])) {
          item[key] = "0.00"
        } else {
          item[key] = (item[key]*1).toFixed(2)
        }
      },
      handleCurrentChange(item){
        this.currentPage3=item
        this.selectGood(item);
      },
      getData(data){
        console.log(data);
        if(!this.material){
          this.material = [];
        }
        var a=0;
        for(var i=0;i<data.length;i++){
          a=0;
          for(let s=0;s<this.material.length;s++){
            if(this.material[s].id==data[i].id){
              a++;
            }
          }
          if(a<=0){
            data[i].value="["+data[i].no+"]"+data[i].name;
            this.material.push(data[i]);
          }
          this.tableData.push({
            id:data[i].id, //规格id
            code:data[i].no,
            name:data[i].name,
            spec:data[i].goodsSpec,
            unit:data[i].unit,
            purchaseSpec:data[i].purchaseSpec,
            unitName:data[i].purchaseUnit,
            count: '0',
            consumeRates:data[i].consumeRates,
            price: data[i].purchasePrice,
            purchaseNewPrice: data[i].purchaseNewPrice,
            money: '0.00',
            memo: '',
            orderPriceBom:data[i].orderPriceBom,
            materialId:data[i].materialId,
            consumeUnit:data[i].consumeUnit,
            value:"["+data[i].no+"]"+data[i].name
          });
        }
        for(var i=0;i<this.tableData.length;i++){
          if(this.tableData[i].purchaseNewPrice==null || this.tableData[i].purchaseNewPrice==''){
            this.tableData[i].purchaseNewPrice=this.tableData[i].purchasePrice;
          }
          if(this.tableData[i].id==''){
            this.tableData.splice(i,1);
          }
        }
        this.dialogTableVisible=false;
      },
      codeChange(index) {
        console.log(this.material);
        for (var i = 0; i < this.material.length; i++) {
          if (this.material[i].no === this.tableData[index].code) {
            this.tableData[index].code = this.material[i].no;
            this.tableData[index].name = this.material[i].name;
            for (var m = 0; m < this.tableData.length; m++) {
              if (this.material[i].id == this.tableData[m].id) {
                this.$message.info("本次添加含有重复原料");
                break;
              }
            }
            this.tableData[index].id = this.material[i].id;
            this.tableData[index].name = this.material[i].name;
            this.tableData[index].code = this.material[i].no;
            this.tableData[index].spec = this.material[i].goodsSpec;
            this.tableData[index].consumeUnit=this.material[i].consumeUnit;
            this.tableData[index].consumeRates=this.material[i].consumeRates;
            this.tableData[index].orderPriceBom=this.material[i].orderPriceBom;
            this.tableData[index].unit = this.material[i].unit;
            this.tableData[index].count = 0;
            this.tableData[index].purchaseNewPrice = this.material[i].purchaseNewPrice;
            break;
          }
        }
      },
      remoteMethod(query) {
        if (query != '') {
          this.loading = true;
          this.$axios.get("branchstores/materialCosts/getMaterialsByName?code="+query).then(data=>{
            this.loading = false;
            if(data.status==200){
              var a=0;
              if(data.content.materials && data.content.materials.length>0){
                for(let i=0;i<data.content.materials.length;i++){
                  a=0;
                  if(this.material && this.tableData && this.tableData.length>0 && this.tableData[0].id){
                    for(let s=0;s<this.material.length;s++){
                      if(this.material[s].id==data.content.materials[i].id){
                        a++;
                      }
                    }
                    if(a<=0){
                      console.log("1materials")
                      if(this.tableData[i].id){
                        this.material.push(data.content.materials[i]);
                      }
                    }
                  }else{
                    console.log("2materials")
                    this.material=data.content.materials;
                    console.log(this.material);
                  }
                }
              }else {
                console.log("3materials")
                this.material=data.content.materials;
              }

            }
          });
        } else {
        }
      },
      selectGood(page){
        this.dialogTableVisible = true;
      },
      handleIconClick(index) {
        if (this.isEdit) {
          return;
        }
        this.dialogTableVisible = true;
        this.itemActive = index;
      },
      handleNodeClick(data) {
        var id=data.id;
        this.content=id;
        this.selectGood();
      },
      tableSelect(row){
        this.selectRow=row;

      },
      checkboxInit(row,index){
        if(row.state && row.state.key!="NORMAL"){
          return 0;//不可勾选
        }else{
          return 1;
        }
      },
      chnageGoodState(row, column, cell, event){
        if(row.state && row.state.key!="NORMAL"){
          return;
        }else{
        }
        this.$refs.multipleTable.toggleRowSelection(row);
      },
      handleSelectionChange(row) {
        this.selectRow = row;
      },
      goBack() {
        this.router.go(-1);
      },
      getSummaries() {
        const sums = [];
        sums[1] = "合计";
        sums[7] = 0;
        sums[9] = 0;
        for(var i=0;i<this.tableData.length;i++){
          var item = this.tableData[i];
          sums[7] += item.count*1;
          if(item.consumeRates>0){
            if(item.orderPriceBom){
              sums[9] += item.orderPriceBom*item.count/item.consumeRates;
            }else {
              sums[9] += 0;
            }
//            sums[9] += item.orderPriceBom*item.count/item.consumeRates;
          }else{
            if(item.orderPriceBom){
              sums[9] += item.orderPriceBom*item.count;
            }else {
              sums[9] += 0;
            }
//            sums[9] += item.orderPriceBom*item.count;
          }
        }
        sums[7] = sums[7].toFixed(4);
        sums[9] = sums[9].toFixed(4);
        this.modelForm.materialCost = sums[9];
        this.modelForm.cost = (this.modelForm.materialCost*1+this.modelForm.otherCost*1).toFixed(4);
        return sums;
      },
      submitForm(formName) {
        if(this.modelForm.warehouseId==null){
          this.$message.error("请选择仓库！");
          return;
        }
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].id == "") {
            if (this.tableData.length == 1) {
              this.$message.error("请添加单据明细！");
              return;
            }
            this.tableData.splice(i, 1);
            i--;
          }
        }
        if (this.tableData == null || this.tableData.length == 0) {
          this.$message.error("请添加单据明细！");
          return;
        }
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].count <= 0) {
            this.$message.error("消耗数量不能小于1！请检查第"+(i+1)+"行数据");
            return;
          }
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var data = {};
            data.modelForm = this.modelForm;
            data.items = this.tableData;
            this.$axios.post("branchstores/materialCosts/create",data,"json").then(data=>{
              if(data.status==200){
                this.$message.success(data.message);
                this.router.go(-1);
              }else{
                this.$message.error(data.message);
              }
            });
          } else {
            this.$message.error("请检查输入项");
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      danjiaJiaoyan(item,key){
        if(key=="shuliang"){
          var r = /^\+?[1-9][0-9]*$/;
          if( ! r.test(item[key])){
            item[key]="0.00"
          }else{
            item[key]=item[key]
          }
          return;
        }
        var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if( ! isNum.test(item[key])){
          item[key]="0.00"
        }else{
          item[key]=item[key]
        }
      },
      addColumn(index){
        if(this.isEdit) {
          return;
        }
        this.tableData.splice(index+1,0,{
          id:"",
          code: '',
          name: '',
          goodsSpec: '',
          purchaseSpec: '',
          consumeUnit:'',
          unit:'',
          unitId:'',
          count:'0',
          orderPriceBom:'0.00',
          price:'0.00',
          newPrice:"0.00",
          memo:'',
          isMain:false,

        })
      },
      minusColumn(index){
        if(this.isEdit) {
          return;
        }
        if(this.tableData.length>1){
          this.tableData.splice(index,1);
        }else{
          this.$message.info("最少保留一条");
        }
      },
      handleSelect(item) {

      },
      querySearchAsync(queryString, cb) {
        var restaurants = this.material;
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 3000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.indexOf(queryString.toLowerCase()) === 0);
        };
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSizeChange(val){
        this.pageSize=val;
        this.selectGood('');
      },
      isDouble(item,key){
        var isNum=/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
        if( ! isNum.test(item[key])){
          item[key]="0.00"
        }else{
          item[key]=item[key]
        }
      }
    },

  }
</script>
<style scoped>
  .el-form-item{
    margin-bottom: 10px !important;
  }
  .el-table tr{
    border-bottom: 1px solid #dfe6ec !important;
  }
</style>
